from fastapi import FastAPI
from apscheduler.schedulers.background import BackgroundScheduler
import time
app = FastAPI()

scheduler = BackgroundScheduler()
scheduler.start()

async def add_task(func, task_id: str, run_date: str, args: list):
    try:
        scheduler.add_job(func, id=task_id, trigger='date', run_date='2024-09-09 21:54', args=args)
    except Exception as e:
        print({"msg": "任务启动失败"})
        return
    print({"msg": "任务启动成功"})


@app.get("/task_list")
async def task_list():
    jobs = scheduler.get_jobs()  # 获取全部的jobs
    jobs_info = []
    for job in jobs:
        info = {}
        info['id'] = job.id
        info['next_run_time'] = job.next_run_time
        jobs_info.append(info)
    return jobs_info


@app.get("/task_pause")
async def task_pause(task_id: str):
    job = scheduler.get_job(task_id)
    if job:
        job.pause()
        return {"msg": "task id 已暂停"}
    else:
        return {"msg": "task id 不存在"}


@app.get("/task_delete")
async def task_del(task_id: str):
    job = scheduler.get_job(task_id)
    if job:
        job.remove()
        return {"msg": "task id 已删除"}
    else:
        return {"msg": "task id 不存在"}


@app.get("/task_resume")
async def task_resume(task_id: str):
    job = scheduler.get_job(task_id)
    if job:
        job.resume()
        return {"msg": "task id 已恢复"}
    else:
        return {"msg": "task id 不存在"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        app='test.main:app',
        host="127.0.0.1",
        port=8020, reload=True
    )
